<template>
  <div class="my-activities">
    <div class="page-header">
      <h2>我的活动</h2>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="已报名" name="enrolled">
        <el-table :data="enrolledActivities" style="width: 100%">
          <el-table-column prop="title" label="活动名称" min-width="200" />
          <el-table-column prop="startTime" label="活动时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="活动地点" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="info" size="small" @click="viewDetails(row)">
                查看详情
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="cancelEnrollment(row)"
                :disabled="!canCancel(row)"
              >
                取消报名
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="已参加" name="completed">
        <el-table :data="completedActivities" style="width: 100%">
          <el-table-column prop="title" label="活动名称" min-width="200" />
          <el-table-column prop="startTime" label="活动时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="活动地点" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="评价" width="200" fixed="right">
            <template #default="{ row }">
              <el-rate
                v-if="row.rating"
                v-model="row.rating"
                disabled
                show-score
                text-color="#ff9900"
              />
              <el-button 
                v-else 
                type="primary" 
                size="small"
                @click="showRatingDialog(row)"
              >
                评价活动
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="ratingDialogVisible"
      title="活动评价"
      width="500px"
    >
      <el-form :model="ratingForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate
            v-model="ratingForm.rating"
            show-score
            text-color="#ff9900"
          />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="ratingForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating">提交评价</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()

// 标签页
const activeTab = ref('enrolled')

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 活动数据
const enrolledActivities = ref([])
const completedActivities = ref([])

// 评价相关
const ratingDialogVisible = ref(false)
const ratingForm = ref({
  activityId: null,
  rating: 0,
  comment: ''
})

// 获取活动列表
const fetchActivities = async () => {
  try {
    const response = await fetch(
      `/api/club/activities/my?type=${activeTab.value}&page=${currentPage.value - 1}&size=${pageSize.value}`
    )
    const data = await response.json()
    if (activeTab.value === 'enrolled') {
      enrolledActivities.value = data.content
    } else {
      completedActivities.value = data.content
    }
    total.value = data.totalElements
  } catch (error) {
    console.error('获取活动列表失败：', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    '未开始': 'info',
    '报名中': 'success',
    '已结束': 'danger',
    '已满': 'warning'
  }
  return types[status] || 'info'
}

// 判断是否可以取消报名
const canCancel = (activity) => {
  return ['未开始', '报名中'].includes(activity.status)
}

// 查看详情
const viewDetails = (activity) => {
  router.push(`/club/activities/${activity.id}`)
}

// 取消报名
const cancelEnrollment = async (activity) => {
  try {
    await ElMessageBox.confirm('确定要取消报名吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await fetch(`/api/club/activities/${activity.id}/enroll`, {
      method: 'DELETE'
    })
    
    ElMessage.success('取消报名成功')
    fetchActivities()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败：', error)
      ElMessage.error('取消报名失败')
    }
  }
}

// 显示评价对话框
const showRatingDialog = (activity) => {
  ratingForm.value = {
    activityId: activity.id,
    rating: 0,
    comment: ''
  }
  ratingDialogVisible.value = true
}

// 提交评价
const submitRating = async () => {
  try {
    if (ratingForm.value.rating === 0) {
      ElMessage.warning('请选择评分')
      return
    }

    await fetch(`/api/club/activities/${ratingForm.value.activityId}/rating`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(ratingForm.value)
    })

    ElMessage.success('评价提交成功')
    ratingDialogVisible.value = false
    fetchActivities()
  } catch (error) {
    console.error('评价提交失败：', error)
    ElMessage.error('评价提交失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchActivities()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchActivities()
}

// 监听标签页切换
watch(activeTab, () => {
  currentPage.value = 1
  fetchActivities()
})

// 初始化
onMounted(() => {
  fetchActivities()
})
</script>

<style lang="scss" scoped>
.my-activities {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .el-tabs {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 